<template>
    <div class="file-manager">
        <!-- 左侧分组列表 -->
        <div class="file-groups">
            <div class="group-item" 
                :class="{ active: currentGroup === 'all' }"
                @click="handleGroupClick('all')"
            >
                <el-icon><Files /></el-icon>
                <span>全部文件</span>
            </div>
            <div class="group-item" 
                v-for="group in groupNames" 
                :key="group"
                :class="{ active: currentGroup === group }"
                @click="handleGroupClick(group)"
            >
                <el-icon><FolderOpened /></el-icon>
                <span>{{ group }}</span>
            </div>
        </div>

        <!-- 右侧文件列表 -->
        <div class="file-content">
            <div class="file-header">
                <div class="left-actions">
                    <div class="search-box">
                        <el-input
                            v-model="searchKeyword"
                            placeholder="搜索文件名"
                            clearable
                            @input="handleSearch"
                        >
                            <template #prefix>
                                <el-icon><search /></el-icon>
                            </template>
                        </el-input>
                    </div>
                </div>
                <div class="right-actions">
                    <el-dropdown v-if="!props.selectable && selectedFiles.length > 0" trigger="click">
                        <el-button type="primary">
                            操作<el-icon class="el-icon--right"><arrow-down /></el-icon>
                        </el-button>
                        <template #dropdown>
                            <el-dropdown-menu>
                                <el-dropdown-item @click="showMoveGroup = true">
                                    <el-icon><folder /></el-icon>移动到分组
                                </el-dropdown-item>
                                <el-dropdown-item @click="handleBatchDelete">
                                    <el-icon><delete /></el-icon>批量删除
                                </el-dropdown-item>
                            </el-dropdown-menu>
                        </template>
                    </el-dropdown>
                    <el-button type="primary" @click="handleUpload">
                        <el-icon><upload-filled /></el-icon>上传文件
                    </el-button>
                </div>
            </div>

            <div class="file-list">
                <el-table 
                    :data="fileList" 
                    @selection-change="handleSelectionChange"
                >
                    <el-table-column 
                        type="selection" 
                        width="55"
                        :selectable="handleSelectable"
                    />
                    <el-table-column label="文件名" min-width="300">
                        <template #default="{ row }">
                            <div class="file-name">
                                <el-icon><component :is="getFileIcon(row.suffix)" /></el-icon>
                                <span>{{ row.name }}</span>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="size" label="大小" width="120">
                        <template #default="{ row }">
                            {{ formatFileSize(row.size) }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="updateTime" label="修改时间" width="180" />
                    <el-table-column v-if="!props.selectable" label="分组" width="200">
                        <template #default="{ row }">
                            <el-dropdown trigger="click" @command="(command) => handleGroupCommand(command, row)">
                                <el-button type="primary" link>
                                    {{ row.groupName || '未分组' }}
                                    <el-icon class="el-icon--right"><arrow-down /></el-icon>
                                </el-button>
                                <template #dropdown>
                                    <el-dropdown-menu>
                                        <el-dropdown-item 
                                            v-for="group in groupNames" 
                                            :key="group"
                                            :command="{ type: 'select', group }"
                                        >
                                            {{ group }}
                                        </el-dropdown-item>
                                        <el-dropdown-item divided>
                                            <el-input
                                                v-model="newGroupName"
                                                placeholder="输入新分组名称"
                                                size="small"
                                                @keyup.enter="(e) => handleNewGroup(e, row)"
                                                @click.stop
                                            >
                                                <template #append>
                                                    <el-button @click="(e) => handleNewGroup(e, row)">
                                                        <el-icon><plus /></el-icon>
                                                    </el-button>
                                                </template>
                                            </el-input>
                                        </el-dropdown-item>
                                    </el-dropdown-menu>
                                </template>
                            </el-dropdown>
                        </template>
                    </el-table-column>
                    <el-table-column v-if="!props.selectable" label="操作" width="150" fixed="right">
                        <template #default="{ row }">
                            <el-button link type="primary" @click="handlePreview(row)">预览</el-button>
                            <el-button link type="primary" @click="handleDownload(row)">下载</el-button>
                            <el-button link type="danger" @click="handleDelete(row)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>

            <!-- 分页 -->
            <div class="pagination-container">
                <div class="pagination-left"></div>
                <div class="pagination-right">
                    <div class="pagination-info" v-if="selectedFiles.length > 0">
                        已选择 {{ selectedFiles.length }} 个文件
                    </div>
                    <el-pagination
                        v-model:current-page="currentPage"
                        v-model:page-size="pageSize"
                        :page-sizes="[10, 20, 50, 100]"
                        :total="total"
                        layout="total, sizes, prev, pager, next"
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                    />
                </div>
            </div>
        </div>

        <!-- 上传组件 -->
        <Upload v-if="!props.selectable" v-model="showUpload" @success="handleUploadSuccess" />

        <!-- 批量移动分组对话框 -->
        <el-dialog v-model="showMoveGroup" title="移动到分组" width="400px">
            <el-form>
                <el-form-item label="选择分组">
                    <el-select v-model="targetGroup" placeholder="请选择分组">
                        <el-option
                            v-for="group in groupNames"
                            :key="group"
                            :label="group"
                            :value="group"
                        />
                        <el-option value="new" label="+ 新建分组">
                            <el-input
                                v-if="targetGroup === 'new'"
                                v-model="newGroupName"
                                placeholder="输入新分组名称"
                                @click.stop
                            />
                            <span v-else>+ 新建分组</span>
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="showMoveGroup = false">取消</el-button>
                    <el-button type="primary" @click="handleBatchMove">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, defineProps, defineEmits, PropType } from 'vue'
import { Search, UploadFilled, Files, FolderOpened, Plus, ArrowDown, Folder, Delete } from '@element-plus/icons-vue'
import { FILE_TYPES, formatFileSize, getFileType } from '@/config/fileTypes'
import { GetFileList, getGroupName, setgroupName, type SysFileResp, type ListParmas, type ListData } from '@/apis/file'
import Upload from '@/components/Upload/index.vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const props = defineProps({
    selectable: {
        type: Boolean,
        default: false
    },
    multiple: {
        type: Boolean,
        default: true
    },
    suffixes: {
        type: Array as PropType<string[]>,
        default: () => []
    }
})

const emit = defineEmits(['select'])

// 状态变量
const showUpload = ref(false)
const fileList = ref<SysFileResp[]>([])
const currentGroup = ref('all')
const searchKeyword = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const groupNames = ref<string[]>([])

// 分组相关
const showMoveGroup = ref(false)
const targetGroup = ref('')
const newGroupName = ref('')

// 选择相关
const selectedFiles = ref<SysFileResp[]>([])

// 获取分组列表
const fetchGroupNames = async () => {
    try {
        const { names } = await getGroupName()
        groupNames.value = names
    } catch (error) {
        console.error('获取分组列表失败:', error)
        ElMessage.error('获取分组列表失败')
    }
}

// 获取文件图标
const getFileIcon = (suffix: string) => {
    const { config } = getFileType(suffix)
    return config.icon
}

// 获取文件列表
const getFileList = async () => {
    try {
        const params: ListParmas = {
            page: currentPage.value,
            pageSize: pageSize.value,
            keyword: searchKeyword.value,
            groupName: currentGroup.value === 'all' ? '' : currentGroup.value,
            suffix: props.suffixes.length > 0 ? props.suffixes.join(',') : undefined
        }
        const { list, total: totalCount } = await GetFileList<ListData>(params)
        fileList.value = list
        total.value = totalCount
    } catch (error) {
        console.error('获取文件列表失败:', error)
        ElMessage.error('获取文件列表失败')
    }
}

// 分组点击
const handleGroupClick = (group: string) => {
    currentGroup.value = group
    currentPage.value = 1 // 重置页码
    getFileList()
}

let Timer:any = null
// 搜索处理
const handleSearch = () => {
    clearTimeout(Timer)
    Timer = setTimeout(() => {
        currentPage.value = 1 // 重置页码
        getFileList()
    }, 500)
}

// 分页处理
const handleSizeChange = (val: number) => {
    pageSize.value = val
    getFileList()
}

const handleCurrentChange = (val: number) => {
    currentPage.value = val
    getFileList()
}

// 选择处理
const handleSelectable = (row: SysFileResp) => {
    // 检查文件后缀是否在允许列表中
    if (props.suffixes.length > 0 && !props.suffixes.includes(row.suffix)) {
        return false
    }
    
    if (!props.multiple && selectedFiles.value.length >= 1) {
        return selectedFiles.value.some(file => file.uUid === row.uUid)
    }
    return true
}

const handleSelectionChange = (files: SysFileResp[]) => {
    selectedFiles.value = files
    emit('select', files)
}

// 上传相关
const handleUpload = () => {
    showUpload.value = true
}

const handleUploadSuccess = () => {
    getFileList()
}

// 文件操作
const handlePreview = (row: SysFileResp) => {
    // TODO: 实现文件预览
    console.log('预览文件:', row)
}

const handleDownload = (row: SysFileResp) => {
    // TODO: 实现文件下载
    console.log('下载文件:', row)
}

const handleDelete = (row: SysFileResp) => {
    // TODO: 实现文件删除
    console.log('删除文件:', row)
}

// 分组操作
const handleGroupCommand = async (command: { type: string, group?: string }, file: SysFileResp) => {
    if (command.type === 'select' && command.group) {
        try {
            await setgroupName({
                uUid: file.uUid,
                groupName: command.group
            })
            ElMessage.success('修改分组成功')
            getFileList()
        } catch (error) {
            console.error('修改分组失��:', error)
            ElMessage.error('修改分组失败')
        }
    }
}

const handleNewGroup = async (e: Event, file: SysFileResp) => {
    e.stopPropagation()
    if (!newGroupName.value.trim()) {
        ElMessage.warning('请输入分组名称')
        return
    }

    try {
        await setgroupName({
            uUid: file.uUid,
            groupName: newGroupName.value.trim()
        })
        ElMessage.success('添加分组成功')
        newGroupName.value = ''
        await fetchGroupNames()
        getFileList()
    } catch (error) {
        console.error('添加分组失败:', error)
        ElMessage.error('添加分组失败')
    }
}

// 批量操作
const handleBatchMove = async () => {
    if (!targetGroup.value) {
        ElMessage.warning('请选择目标分组')
        return
    }

    const groupName = targetGroup.value === 'new' ? newGroupName.value.trim() : targetGroup.value

    if (targetGroup.value === 'new' && !groupName) {
        ElMessage.warning('请输入新分组名称')
        return
    }

    try {
        for (const file of selectedFiles.value) {
            await setgroupName({
                uUid: file.uUid,
                groupName
            })
        }
        ElMessage.success('批量移动成功')
        showMoveGroup.value = false
        targetGroup.value = ''
        newGroupName.value = ''
        await fetchGroupNames()
        getFileList()
    } catch (error) {
        console.error('批量移动失败:', error)
        ElMessage.error('批量移动失败')
    }
}

const handleBatchDelete = () => {
    ElMessageBox.confirm(
        `确定要删除选中的 ${selectedFiles.value.length} 个文件吗？`,
        '警告',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    ).then(async () => {
        try {
            // TODO: 实现批量删除
            ElMessage.success('批量删除成功')
            getFileList()
        } catch (error) {
            console.error('批量删除失败:', error)
            ElMessage.error('批量删除失败')
        }
    })
}

// 初始化
onMounted(async () => {
    await fetchGroupNames()
    getFileList()
})
</script>

<style scoped lang="scss">
.file-manager {
    display: flex;
    height: 100%;
    background-color: var(--el-bg-color);

    .file-groups {
        width: 200px;
        padding: 20px 0;
        border-right: 1px solid var(--el-border-color-light);
        background-color: var(--el-bg-color-overlay);

        .group-item {
            display: flex;
            align-items: center;
            padding: 12px 20px;
            cursor: pointer;
            transition: background-color 0.3s;

            &:hover {
                background-color: var(--el-fill-color-light);
            }

            &.active {
                background-color: var(--el-color-primary-light-9);
                color: var(--el-color-primary);
            }

            .el-icon {
                margin-right: 8px;
                font-size: 18px;
            }
        }
    }

    .file-content {
        flex: 1;
        padding: 20px;
        overflow: auto;

        .file-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            gap: 16px;

            .left-actions {
                display: flex;
                align-items: center;
                gap: 16px;

                .search-box {
                    width: 300px;
                }
            }

            .right-actions {
                display: flex;
                gap: 8px;
            }
        }

        .file-list {
            .file-name {
                display: flex;
                align-items: center;
                gap: 8px;
            }
        }

        .pagination-container {
            margin-top: 20px;
            display: flex;
            justify-content: space-between;

            .pagination-left {
                flex: 1;
            }

            .pagination-right {
                display: flex;
                align-items: center;
                gap: 16px;

                .pagination-info {
                    color: var(--el-text-color-secondary);
                    font-size: 14px;
                }
            }
        }
    }
}

:deep(.el-dropdown-menu__item) {
    display: flex;
    align-items: center;
    gap: 8px;
    
    .el-icon {
        margin-right: 4px;
    }
}
</style> 